package com.kstech.mp3604.base


import android.annotation.SuppressLint
import android.view.View
import android.widget.AdapterView
import android.widget.AdapterView.OnItemSelectedListener
import android.widget.ArrayAdapter
import androidx.fragment.app.activityViewModels
import com.blankii.androidlibrary.base.BaseBindingFragment
import com.blankii.androidlibrary.exts.logd
import com.blankii.androidlibrary.utils.ViewClickContinuousUtil
import com.blankj.utilcode.util.SPUtils
import com.kstech.mp3604.R
import com.kstech.mp3604.base.Global.DZ_WEIGHT
import com.kstech.mp3604.base.Global.PIANCHA
import com.kstech.mp3604.base.Global.PIANCHA_Y
import com.kstech.mp3604.base.Global.VIDEO_URL_1
import com.kstech.mp3604.base.Global.WARE_HOUSE_ID
import com.kstech.mp3604.base.Global.app_wareHouse
import com.kstech.mp3604.bean.Data4
import com.kstech.mp3604.bean.ErrorInfo
import com.kstech.mp3604.bean.Log
import com.kstech.mp3604.bean.StackCoordinate
import com.kstech.mp3604.data.DbManager
import com.kstech.mp3604.databinding.FragmentDmBinding
import com.kstech.mp3604.fragments.DialogConfirmNoTaskFragment
import com.kstech.mp3604.fragments.DialogConfirmTaskFinishedFragment
import com.kstech.mp3604.fragments.DialogConfirmTaskFragment
import com.kstech.mp3604.fragments.DialogErrorFragment
import com.kstech.mp3604.fragments.DialogQueryDataFragment
import com.kstech.mp3604.fragments.DialogSetWareHouseFragment
import com.kstech.mp3604.fragments.DialogSettingFragment
import com.kstech.mp3604.fragments.DialogTaskFragment
import com.kstech.mp3604.fragments.DialogTestSocketFragment
import com.kstech.mp3604.manager.CameraManager
import com.kstech.mp3604.manager.ShowDialogConfirmFinished
import com.kstech.mp3604.manager.SoundManager
import com.kstech.mp3604.manager.StackNumberManager
import com.kstech.mp3604.manager.serialComm.SerialManager
import com.kstech.mp3604.manager.socket.SocketManager
import com.kstech.mp3604.manager.socket.SocketManager.sendNoTaskData
import com.kstech.mp3604.manager.socket.SocketManager.sendTaskData
import com.kstech.mp3604.manager.socket.SocketMsgListener
import com.kstech.mp3604.ui.listener.DialogConfirmNoTaskListener
import com.kstech.mp3604.ui.listener.DialogConfirmTaskFinishedListener
import com.kstech.mp3604.ui.listener.DialogConfirmTaskListener
import com.kstech.mp3604.ui.listener.SettingNewDialogListener
import com.kstech.mp3604.ui.listener.TaskSelectListener
import com.kstech.mp3604.utils.ThreadUtil
import com.kstech.mp3604.utils.TimeUtil
import com.kstech.xz3604.ui.ViewShanManager
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import kotlin.math.max

/**
 * 主 fragment
 *
 * mTask 没有初始化的时候为项目最初始化状态
 * 当mTask 初始化之后 任务栏显示的时候-有任务   任务栏隐藏-无任务
 *
 *
 * ************can通讯显示逻辑***********
 * 系统状态0410-byte0-bit0 应急为1时 隐藏不相干view，应急闪烁语音播报
 * 系统状态0410-byte0-bit1 自动回正为1时 同上
 * 系统状态0410-byte0-bit2 自动回位为1时 同上
 * 系统状态0410-byte0-bit3 0直线 1曲线
 * 系统状态0410-byte0-bit4 故障 故障灯闪烁
 * 系统状态0410-byte0-bit5 0行走 1堆码   堆码时开启摄像头，否则关闭摄像头
 * 系统状态0410-byte2-bit0 0实时重量 1起吊完成
 * 系统状态0410-byte3-byte4 吊装 kg
 * 系统状态0410-byte5 故障设备
 * 系统状态0410-byte6-byte7 故障码
 *
 *
 *
 * *************故障灯逻辑***************
 * can通讯与socket通讯均连通之后        绿灯
 * 有一个通讯失败                      红灯
 * 接收到控制器通讯故障报警时            红灯并闪烁
 * 红灯并闪烁点击                      弹出确认对话框，不闪烁点不出来
 * 确认对话框确认后                    五分钟之内收到故障报警均不会红灯并闪烁
 *
 *
 *
 * *************有任务、无任务***********
 * 任务单受领任务          有任务
 * 展开任务栏按钮          有任务
 * 双击隐藏任务栏          无任务
 * 初始化进入界面          无任务
 *
 * 有任务状态              显示任务栏
 * 无任务状态              隐藏任务栏
 *
 *
 */
class DmFragment : BaseBindingFragment<FragmentDmBinding>(FragmentDmBinding::inflate),
    SocketMsgListener, TaskSelectListener, SettingNewDialogListener,
    SerialManager.Rev_0210_Listener, SerialManager.Rev_0310_Listener,
    SerialManager.Rev_0410_Listener, DialogConfirmTaskListener, CameraManager.CameraUIListener,
    DialogConfirmNoTaskListener, ShowDialogConfirmFinished, DialogConfirmTaskFinishedListener {
    private lateinit var mStack: StackCoordinate
    private var serialSound = false
    private val homeViewModel: HomeViewModel by activityViewModels()
    override fun onCreateInit() {
        SocketManager.bindSocketMsgListener(this)
        CameraManager.setListener(this)
    }

    override fun onInitView() {
        /**
         * 初始化listener
         */
        StackNumberManager.setListener(this)
        /**
         * 初始化一些view状态，绑定点击事件
         */
        initView()
        /**
         * 查询是否绑定仓库
         */
        checkIsBindWareHouse()
        /**
         * viewModel 监控liveData
         */
        homeViewModel.isTasking.observe(this) { result ->
            if (result) {
                changeToTaskState()
            } else {
                if (homeViewModel.dataInit.value == true) {
                    changeToNoTaskState()
                }
            }
        }
    }


    private fun checkIsBindWareHouse() {
        val whId = SPUtils.getInstance().getString(WARE_HOUSE_ID)
        if (whId.isNullOrEmpty()) {
            showBindWareHouseDialog()
        } else {
            app_wareHouse = whId
        }
    }

    override fun newMsg() {
        ViewShanManager.open(binding.taskNotify)
    }

    override fun showEmptyWareHouseIdDialog() {
        DialogSetWareHouseFragment().show(parentFragmentManager)
    }

    @SuppressLint("SetTextI18n")
    private fun initView() {
        binding.apply {
            val spinnerAdapter = ArrayAdapter<String>(
                requireContext(), R.layout.layout_item_spinner_item, Global.typeNameArr
            )
            distancePart1.visibility = View.GONE
            distancePart2.visibility = View.GONE
            distancePart3.visibility = View.GONE
            distanceAllPart.visibility = View.GONE
            spinnerView.adapter = spinnerAdapter
            spinnerView.visibility = View.VISIBLE
            videoView.visibility = View.INVISIBLE
            yingjiLayout.visibility = View.INVISIBLE
            zidonghuiweiLayout.visibility = View.INVISIBLE
            zidonghuizhengLayout.visibility = View.INVISIBLE
            taskPart.visibility = View.GONE
            taskButton.setOnClickListener {
                binding.taskNotify.visibility = View.GONE
                DialogTaskFragment(this@DmFragment).show(parentFragmentManager)
                ThreadUtil.executeIOFun {
                    DbManager.db.logDao().addLog(
                        Log(
                            time = TimeUtil.getDateTimeStr(), content = "操作人员-点击任务单按钮"
                        )
                    )
                }
            }
            errorButton.setOnClickListener {
                DialogErrorFragment().show(parentFragmentManager)
                ThreadUtil.executeIOFun {
                    DbManager.db.logDao().addLog(
                        Log(
                            time = TimeUtil.getDateTimeStr(), content = "操作人员-点击故障按钮"
                        )
                    )
                }
            }
            queryButton.setOnClickListener {
//                showQueryDialog()
//                MyDialogFragment2().show(parentFragmentManager,"123")
                DialogQueryDataFragment().show(parentFragmentManager)
                ThreadUtil.executeIOFun {
                    DbManager.db.logDao().addLog(
                        Log(
                            time = TimeUtil.getDateTimeStr(), content = "操作人员-点击查询按钮"
                        )
                    )
                }
            }
            settingButton.setOnClickListener {
                DialogSettingFragment(this@DmFragment).show(parentFragmentManager)
                ThreadUtil.executeIOFun {
                    DbManager.db.logDao().addLog(
                        Log(
                            time = TimeUtil.getDateTimeStr(), content = "操作人员-点击设置按钮"
                        )
                    )
                }
            }
            /**
             *展开任务栏
             */
            extendTaskView.visibility = View.INVISIBLE
            extendTaskView.setOnClickListener {
                if (homeViewModel.dataInit.value == true) {
                    homeViewModel.isTasking.value = true
                }
            }
            /**
             * 任务栏连点隐藏
             */
            ViewClickContinuousUtil.setViewConfig(
                binding.taskPart,
                callBack = object : ViewClickContinuousUtil.ClickContinuousCallback {
                    override fun currentCount(count: Int) {

                    }

                    override fun success() {
                        DialogConfirmNoTaskFragment(this@DmFragment).show(parentFragmentManager)

                    }
                })
            /**
             * 弹药类型
             * spinnerView 如果当前position=1 即使setSelection(1) 不会触发点击事件，因为他有新旧数据判断
             */
            binding.spinnerView.onItemSelectedListener = object : OnItemSelectedListener {
                override fun onItemSelected(
                    p0: AdapterView<*>?, p1: View?, position: Int, p3: Long
                ) {
                    //同步速度限制
                    Global.currentSpeedQS = Global.speedQS[position]
                    Global.currentSpeedHY = Global.speedHY[position]
                    Global.currentSpeedJC = Global.speedJC[position]

//                    "===========>".loge(TAG)
                }

                override fun onNothingSelected(p0: AdapterView<*>?) {
                    // 当没有选择任何项时调用
                }
            }
            homeViewModel.isTasking.observe(this@DmFragment) { result ->
                if (result) {
                    binding.distanceAllPart.visibility = View.VISIBLE
                    if (homeViewModel.dataInit.value == true) {
                        Global.currentSpeedQS =
                            (mStack.taskData.liftingSpecification.liftingSpeed * 1000).toInt()
                        Global.currentSpeedJC =
                            (mStack.taskData.liftingSpecification.approachSpeed * 1000).toInt()
//                        Global.currentSpeedHZ =
//                            (mStack.taskData.liftingSpecification.rotationSpeed * 1000).toInt()
                        Global.currentSpeedHY =
                            (mStack.taskData.liftingSpecification.horizontalSpeed * 1000).toInt()
                    }
                } else {
                    binding.distanceAllPart.visibility = View.GONE
                    spinnerView.setSelection(Global.typeNameArr.lastIndex)
                    Global.currentSpeedQS = Global.speedQS[Global.typeNameArr.lastIndex]
                    Global.currentSpeedHY = Global.speedHY[Global.typeNameArr.lastIndex]
//                    Global.currentSpeedHZ = Global.speedHZ[Global.typeNameArr.lastIndex]
                    Global.currentSpeedJC = Global.speedJC[Global.typeNameArr.lastIndex]
                }
            }
            /**
             * 动态显示X,Y,Z
             */
            homeViewModel.device_posX.observe(this@DmFragment) { value ->
                binding.xValue.text = "X轴:${value + PIANCHA}"
            }
            homeViewModel.device_posY.observe(this@DmFragment) { value ->
                binding.yValue.text = "Y轴:${value - PIANCHA_Y}"
            }
            homeViewModel.device_posZ.observe(this@DmFragment) { value ->
                binding.zValue.text = "Z轴:${value}"
            }
        }
    }


    private fun changeToTaskState() {
        SoundManager.stop(8)
        binding.taskPart.visibility = View.VISIBLE
        binding.extendTaskView.visibility = View.INVISIBLE

        if (!serialSound) {
            binding.spinnerView.visibility = View.INVISIBLE
            binding.distanceAllPart.visibility = View.VISIBLE
            binding.dmCarModel.visibility = View.VISIBLE
//            binding.yValue.visibility = View.VISIBLE
        }
        //判断定堆放、起吊标志位
        //这里可以切换sjState = false，但是要提示对话框，不然做任务的时候吊起之后切换这么一下，堆放完成无法判定了
//        sjState = false
    }

    private fun changeToNoTaskState() {
        SoundManager.start(requireContext(), 8)
        binding.taskPart.visibility = View.GONE
        binding.distanceAllPart.visibility = View.GONE
        binding.spinnerView.visibility = View.VISIBLE
//        binding.yValue.visibility = View.VISIBLE
        if (homeViewModel.dataInit.value == true) {
            binding.extendTaskView.visibility = View.VISIBLE
        } else {
            binding.extendTaskView.visibility = View.INVISIBLE
        }

        //判断定堆放、起吊标志位
//        sjState = false
    }


    /**
     * 更新任务
     */
    @SuppressLint("SetTextI18n")
    private fun updateTaskPart() {
        //当前任务
        binding.apply {
            //初始化
            qssd.visibility = View.GONE
            hysd.visibility = View.GONE
            jjsd.visibility = View.GONE
            hzsd.visibility = View.GONE

            warehouseId.text = "仓库Id:${mStack.taskData.warehouseId}"
            taskId.text = "任务Id:${mStack.taskData.taskId}"
            xh.text = "型号:${mStack.taskData.productName}"
            cj.text = "厂家:${mStack.taskData.manufacture}"
            if (mStack.taskData.liftingSpecification.liftingSpeed != 0.0) {
                qssd.text = "起升速度:${mStack.taskData.liftingSpecification.liftingSpeed}(m/min)"
                qssd.visibility = View.VISIBLE
            }
            if (mStack.taskData.liftingSpecification.horizontalSpeed != 0.0) {
                hysd.text =
                    "横移速度:${mStack.taskData.liftingSpecification.horizontalSpeed}(m/min)"
                hysd.visibility = View.VISIBLE
            }
            if (mStack.taskData.liftingSpecification.approachSpeed != 0.0) {
                jjsd.text = "接近速度:${mStack.taskData.liftingSpecification.approachSpeed}(m/min)"
                jjsd.visibility = View.VISIBLE
            }
            if (mStack.taskData.liftingSpecification.rotationSpeed != 0.0) {
                hzsd.text = "回转速度:${mStack.taskData.liftingSpecification.rotationSpeed}(r/min)"
                hzsd.visibility = View.VISIBLE
            }
            hj.text = "行距:${mStack.taskData.saveSpecification.rowSpacing}(mm)"
            lj.text = "列距:${mStack.taskData.saveSpecification.colSpacing}(mm)"
            cs.text = "层数:${mStack.taskData.saveSpecification.floorNumber}"

            safeDistance.text = "到边距:${mStack.taskData.safeDistance / 10}(cm)"

            weight.text = "重量:0(kg)"
        }
    }

    override fun showStartPointDialog() {
        "与控制器通讯,原点标定完成".showSnackBar()
    }

    override fun showBindWareHouseDialog() {
        DialogSetWareHouseFragment().show(parentFragmentManager)
    }

    override fun showTestSocketDialog() {
        if (homeViewModel.dataInit.value == false) {
            "task对象没有初始化，受领一份任务重新进入".showSnackBar()
            return
        }
        DialogTestSocketFragment(mStack).show(parentFragmentManager)
    }

    override fun showTestUiDialog() {

    }

    fun hideSomeViews() {
//        binding.yValue.visibility = View.INVISIBLE
        binding.dmCarModel.visibility = View.INVISIBLE
        binding.distanceAllPart.visibility = View.GONE
//        binding.leftDistance.visibility = View.INVISIBLE
//        binding.rightDistance.visibility = View.INVISIBLE

        binding.spinnerView.visibility = View.INVISIBLE

    }

    fun showSomeViews() {
//        binding.yValue.visibility = View.VISIBLE
        binding.dmCarModel.visibility = View.VISIBLE
        if (homeViewModel.isTasking.value == true) {
            binding.distanceAllPart.visibility = View.VISIBLE
        } else {
            binding.spinnerView.visibility = View.VISIBLE
        }
    }


    //显示直线
    fun showZhiXian(k: Int) {
        if (k == 1) {
            binding.dmCarModel.setImageResource(R.drawable.dm_zhuanwan)
        } else {
            binding.dmCarModel.setImageResource(R.drawable.dm_zhixian)
        }
    }


    /**
     * 行进速度	±99.99	0.001m/min
     * 横移速度	±99.99	0.001m/min
     * 起升速度	±99.99	0.001m/min
     * 接近速度	±99.99	0.001m/min
     *
     * 起吊过程中的最大值发送给信息管理系统 发送起吊完成清零
     * 堆码过程中的最大值发送给信息管理系统 发送堆码完成清零
     */
    override fun data_0210(
        data1: Int, data2: Int, data3: Int, data4: Int
    ) {
        Global.mSpeedQS = max(Global.mSpeedQS, data3)
        Global.mSpeedHY = max(Global.mSpeedHY, data2)
        Global.mSpeedJC = max(Global.mSpeedJC, data4)
    }

    fun clearAllSpeed() {
        Global.mSpeedHY = 0
        Global.mSpeedJC = 0
        Global.mSpeedQS = 0
    }

    /**
     * 位置X	±	0.001m
     * Y	±32.767m	0.001m
     * Z	±32.767m	0.001m
     * 发给15所
     */
    @SuppressLint("SetTextI18n")
    override fun data_0310(data1: Long, data2: Int, data3: Int) {
//        "data1:$data1,data2:$data2,data3:$data3".logd("Blankii")
        homeViewModel.device_posX.value = data1
        homeViewModel.device_posY.value = data2
        homeViewModel.device_posZ.value = data3
        updateDistance(data1)
    }

    @SuppressLint("SetTextI18n")
    private fun updateDistance(x: Long) {

        /**
         * 1 无任务的时候全部隐藏
         * 2 有任务的时候，倒垛显示倒垛并加载数据； 其他任务显示距离目标
         * 3 有任务的时候，入库以及出库显示距离目标
         */
        if (homeViewModel.dataInit.value == true) {
            var operateType = mStack.taskData.operateType
            when (operateType) {
                //倒垛任务
                "REARRANGE" -> {
                    binding.apply {
                        distancePart1.visibility = View.VISIBLE
                        distancePart2.visibility = View.VISIBLE
                        distancePart3.visibility = View.GONE
                        distanceStart.text =
                            "${"%.1f".format((mStack.x - x - PIANCHA).toDouble() / 1000)}m"
                        distanceEnd.text =
                            "${"%.1f".format((mStack.rearrange_x!! - x - PIANCHA).toDouble() / 1000)}m"
                    }
                }
                //其他任务 入库出库
                else -> {
                    binding.apply {
                        binding.textView35.text = "距离目标:"
                        distancePart1.visibility = View.GONE
                        distancePart2.visibility = View.GONE
                        distancePart3.visibility = View.VISIBLE
                        distance.text =
                            "${"%.1f".format((mStack.x - x - PIANCHA).toDouble() / 1000)}m"
                    }
                }
            }

        } else {
            binding.textView35.text = "距离零点:"
            binding.distance.text = "${"%.1f".format((x.toDouble()) / 1000)}m"
        }
    }

    private var lastFaultCode = ""

    /**
     * 故障索引
     * 故障码
     * 为了避免存储重复数据lastFaultCode 用来记录上一个数据如果重复也不记录
     * lastFaultCode格式： 例子 data1=0 data2=0000（十六进制）  lastFaultCode=0-0000
     */
    override fun data1_0410(data1: Int, data2: String) {
        if (data2 == "0000" || lastFaultCode == "$data1-$data2") {
            return
        } else {
            //触发存储
            lastFaultCode = "$data1-$data2"
            CoroutineScope(Dispatchers.IO).launch {
                DbManager.db.errorInfoDao().addErrorInfo(
                    ErrorInfo(
                        time = TimeUtil.getDateTimeStr(), content = FaultNameData.get(data1, data2)
                    )
                )
            }
        }
    }


    /**
     * 系统状态	应急	"自动回正（行走）"	"自动回位吊具）"
     */
    override fun data2_0410(data1: Int, data2: Int, data3: Int) {
        if (data1 == 0 && data2 == 0 && data3 == 0) {
            serialSound = false
            showSomeViews()
            ViewShanManager.close(binding.yingjiLayout)
            ViewShanManager.close(binding.zidonghuizhengLayout)
            ViewShanManager.close(binding.zidonghuiweiLayout)
            binding.yingjiLayout.visibility = View.INVISIBLE
            binding.zidonghuiweiLayout.visibility = View.INVISIBLE
            binding.zidonghuizhengLayout.visibility = View.INVISIBLE
            SoundManager.stop()
        } else if (data1 == 1 && data2 == 0 && data3 == 0) {
            hideSomeViews()
            serialSound = true
            ViewShanManager.open(binding.yingjiLayout, true)
            ViewShanManager.close(binding.zidonghuizhengLayout)
            ViewShanManager.close(binding.zidonghuiweiLayout)
            binding.zidonghuizhengLayout.visibility = View.INVISIBLE
            binding.zidonghuiweiLayout.visibility = View.INVISIBLE
            SoundManager.start(requireContext(), 1)
        } else if (data1 == 0 && data2 == 1 && data3 == 0) {
            hideSomeViews()
            serialSound = true
            ViewShanManager.open(binding.zidonghuizhengLayout, true)
            ViewShanManager.close(binding.yingjiLayout)
            ViewShanManager.close(binding.zidonghuiweiLayout)
            binding.yingjiLayout.visibility = View.INVISIBLE
            binding.zidonghuiweiLayout.visibility = View.INVISIBLE
            SoundManager.start(requireContext(), 2)
        } else if (data1 == 0 && data2 == 0 && data3 == 1) {
            hideSomeViews()
            serialSound = true
            ViewShanManager.open(binding.zidonghuiweiLayout, true)
            ViewShanManager.close(binding.yingjiLayout)
            ViewShanManager.close(binding.zidonghuizhengLayout)
            binding.zidonghuizhengLayout.visibility = View.INVISIBLE
            binding.yingjiLayout.visibility = View.INVISIBLE
            SoundManager.start(requireContext(), 3)
        } else if (data1 == 1 && data2 == 1 && data3 == 0) {
            hideSomeViews()
            serialSound = true
            ViewShanManager.open(binding.yingjiLayout, true)
            ViewShanManager.open(binding.zidonghuizhengLayout, true)
            ViewShanManager.close(binding.zidonghuiweiLayout)

            binding.zidonghuizhengLayout.visibility = View.INVISIBLE
            SoundManager.start(requireContext(), 4)
        } else if (data1 == 1 && data2 == 0 && data3 == 1) {
            hideSomeViews()
            serialSound = true
            ViewShanManager.open(binding.yingjiLayout, true)
            ViewShanManager.open(binding.zidonghuiweiLayout, true)
            ViewShanManager.close(binding.zidonghuizhengLayout)
            binding.zidonghuizhengLayout.visibility = View.INVISIBLE
            SoundManager.start(requireContext(), 5)
        } else if (data1 == 0 && data2 == 1 && data3 == 1) {
            hideSomeViews()
            serialSound = true
            ViewShanManager.open(binding.zidonghuizhengLayout, true)
            ViewShanManager.open(binding.zidonghuiweiLayout, true)
            ViewShanManager.close(binding.yingjiLayout)
            binding.yingjiLayout.visibility = View.INVISIBLE
            SoundManager.start(requireContext(), 6)
        } else if (data1 == 1 && data2 == 1 && data3 == 1) {
            hideSomeViews()
            serialSound = true
            ViewShanManager.open(binding.yingjiLayout, true)
            ViewShanManager.open(binding.zidonghuizhengLayout, true)
            ViewShanManager.open(binding.zidonghuiweiLayout, true)
            SoundManager.start(requireContext(), 7)
        }
    }

    /**
     * 	"0直线1弧线"	故障
     */
    override fun data4_0410(
        data1: Int, data2: Int, data3: Int
    ) {
        showZhiXian(data1)
        if (data2 == 1) {
            homeViewModel.serialIsFault = true
            homeViewModel.device_state.value = Global.RunningStatus.FAULT
        } else {
            homeViewModel.serialIsFault = false
        }

        if (data3 == 1) {
            CameraManager.openCamera()
        } else {
            CameraManager.closeCamera()
        }
    }

    /**
     * 在线状态	线控在线	左转电机在线	右转电机在线	左驱电机在线	右驱电机在线	吊装在线
     */
    override fun data3_0410(
        data1: Int, data2: Int, data3: Int, data4: Int, data5: Int, data6: Int
    ) {


    }


    override fun onResume() {
        super.onResume()
        SerialManager.setRev0210Listener(this)
        SerialManager.setRev0310Listener(this)
        SerialManager.setRev0410Listener(this)

        if (homeViewModel.dataInit.value == true) {
            homeViewModel.isTasking.value = true
            updateTaskPart()
        } else {
            homeViewModel.isTasking.value = false
        }
    }

    override fun onPause() {
        super.onPause()
        SerialManager.clearAllListener()
    }


    /**
     * 升降状态
     * 起吊完成：true
     * 堆放完成：false
     * 保证一次起吊 一次放下只发一次
     *
     * ***每一次有任务、无任务的切换 将其重新设为false***
     * true:正在起吊，只能堆放
     * false:堆放完成，只能起吊
     * */
    private var sjState = false

    /**
     * 吊重	65536kg
     * 无重量->有重量 起吊  起吊的过程重量肯定由零增大 控制器过滤了吗？
     * 有重量->无重量 放下  0 起吊
     */
    @SuppressLint("SetTextI18n")
    override fun data5_0410(data1: Int, dzState: Int) {
        binding.weight.text = "重量:$data1.0kg"
        homeViewModel.device_weight.value = data1
        /**
         * 当数据初始化之后才执行发送
         * 满足重量变化差值 要发送起吊状态
         *
         */
        "data1:$data1,sjState:$sjState,deviceType:${homeViewModel.device_state.value!!.data}".logd("socket-吊重")
        //有任务的起吊
        if (data1 >= DZ_WEIGHT && dzState == 1 && !sjState && homeViewModel.isTasking.value == true && homeViewModel.dataInit.value == true) {
            //由空到有重物 起吊完成，可以发送
            "weight:$data1,sjState:$sjState".logd("实时状态-吊重-有任务-起吊完成")
            "socket-吊重-有任务-起吊完成".showSnackBar()
            sjState = true
            if (!homeViewModel.serialIsFault) {
                homeViewModel.device_state.value = Global.RunningStatus.QD_FINISHED
            }

            sendTaskData(
                Data4(
                    taskId = mStack.taskData.taskId,
                    location = 0,
                    state = homeViewModel.device_state.value!!.data,
                    weight = data1 * 1000.0,
                    homeViewModel.device_posX.value!!.toInt() + PIANCHA,
                    homeViewModel.device_posY.value!! - PIANCHA_Y,
                    homeViewModel.device_posZ.value!!,
                    liftingSpeed = Global.mSpeedQS / 1000.0,
                    rotationSpeed = 0.0,
                    horizontalSpeed = Global.mSpeedHY / 1000.0,
                    approachSpeed = Global.mSpeedJC / 1000.0,
                    time = TimeUtil.getTimeStamp(),
                    operateType = mStack.taskData.operateType,
                    transferOrderNo = mStack.taskData.transferOrderNo,
                    deviceIp = SocketManager.ipAddress,
                    warehouseId = app_wareHouse
                )
            )
            clearAllSpeed()
            //有任务的堆放
        } else if (data1 < DZ_WEIGHT && sjState && homeViewModel.isTasking.value == true && homeViewModel.dataInit.value == true) {
            "weight:$data1,sjState:$sjState".logd("实时状态-吊重-有任务-堆放完成")
            "socket-吊重-有任务-堆放完成".showSnackBar()
            //堆码成功，可以发送
            sjState = false
            if (!homeViewModel.serialIsFault) {
                homeViewModel.device_state.value = Global.RunningStatus.DM_FINISHED
            }
            sendTaskData(
                Data4(
                    taskId = mStack.taskData.taskId,
                    location = 0,
                    state = homeViewModel.device_state.value!!.data,
                    weight = data1 * 1000.0,
                    homeViewModel.device_posX.value!!.toInt() + PIANCHA,
                    homeViewModel.device_posY.value!! - PIANCHA_Y,
                    homeViewModel.device_posZ.value!!,
                    liftingSpeed = Global.mSpeedQS / 1000.0,
                    rotationSpeed = 0.0,
                    horizontalSpeed = Global.mSpeedHY / 1000.0,
                    approachSpeed = Global.mSpeedJC / 1000.0,
                    time = TimeUtil.getTimeStamp(),
                    operateType = mStack.taskData.operateType,
                    transferOrderNo = mStack.taskData.transferOrderNo,
                    deviceIp = SocketManager.ipAddress,
                    warehouseId = app_wareHouse
                )
            )
            StackNumberManager.increaseCount()
            clearAllSpeed()
        } //无任务的起吊
        else if (data1 >= DZ_WEIGHT && dzState == 1 && !sjState && homeViewModel.isTasking.value == false) {
            //由空到有重物 起吊完成，可以发送
            "weight:$data1,sjState:$sjState".logd("实时状态-吊重-无任务-起吊完成")
            "socket-吊重-无任务-起吊完成".showSnackBar()
            sjState = true
            if (!homeViewModel.serialIsFault) {
                homeViewModel.device_state.value = Global.RunningStatus.QD_FINISHED
            }
            sendNoTaskData(
                Data4(
                    taskId = "",
                    location = 0,
                    state = homeViewModel.device_state.value!!.data,
                    weight = data1 * 1000.0,
                    homeViewModel.device_posX.value!!.toInt() + PIANCHA,
                    homeViewModel.device_posY.value!! - PIANCHA_Y,
                    homeViewModel.device_posZ.value!!,
                    liftingSpeed = Global.mSpeedQS / 1000.0,
                    rotationSpeed = 0.0,
                    horizontalSpeed = Global.mSpeedHY / 1000.0,
                    approachSpeed = Global.mSpeedJC / 1000.0,
                    time = TimeUtil.getTimeStamp(),
                    operateType = "",
                    transferOrderNo = "0",
                    deviceIp = SocketManager.ipAddress,
                    warehouseId = app_wareHouse
                )
            )
            clearAllSpeed()
            //无任务的堆放
        } else if (data1 < DZ_WEIGHT && sjState && homeViewModel.isTasking.value == false) {
            "weight:$data1,sjState:$sjState".logd("实时状态-吊重-无任务-堆放完成")
            "socket-吊重-无任务-堆放完成".showSnackBar()
            //堆码成功，可以发送
            sjState = false
            if (!homeViewModel.serialIsFault) {
                homeViewModel.device_state.value = Global.RunningStatus.DM_FINISHED
            }

            sendNoTaskData(
                Data4(
                    taskId = "",
                    location = 0,
                    state = homeViewModel.device_state.value!!.data,
                    weight = data1 * 1000.0,
                    homeViewModel.device_posX.value!!.toInt() + PIANCHA,
                    homeViewModel.device_posY.value!! - PIANCHA_Y,
                    homeViewModel.device_posZ.value!!,
                    liftingSpeed = Global.mSpeedQS / 1000.0,
                    rotationSpeed = 0.0,
                    horizontalSpeed = Global.mSpeedHY / 1000.0,
                    approachSpeed = Global.mSpeedJC / 1000.0,
                    time = TimeUtil.getTimeStamp(),
                    operateType = "",
                    transferOrderNo = "0",
                    deviceIp = SocketManager.ipAddress,
                    warehouseId = app_wareHouse
                )
            )
            clearAllSpeed()
        } else if (data1 < DZ_WEIGHT && !homeViewModel.serialIsFault) {
            homeViewModel.device_state.value = Global.RunningStatus.NOLOAD
        } else if (data1 >= DZ_WEIGHT && !homeViewModel.serialIsFault) {
            homeViewModel.device_state.value = Global.RunningStatus.WITHLOAD
        }
    }

    override fun data6_0410(data1: Int, data2: Int, data3: Int) {

    }


    override fun showConfirmDialog(stack: StackCoordinate) {
        DialogConfirmTaskFragment(stack, this).show(parentFragmentManager)
    }

    /**
     * 确认受领对话框确认回调
     */
    override fun confirmTask(stack: StackCoordinate) {
        mStack = stack
        StackNumberManager.setSumStackNumber(stack.boxNumber)
        homeViewModel.dataInit.value = true
        homeViewModel.isTasking.value = true
        updateTaskPart()

        Global.currentSpeedQS = (stack.taskData.liftingSpecification.liftingSpeed * 1000).toInt()
        Global.currentSpeedJC = (stack.taskData.liftingSpecification.approachSpeed * 1000).toInt()
//        Global.currentSpeedHZ = (stack.taskData.liftingSpecification.rotationSpeed * 1000).toInt()
        Global.currentSpeedHY = (stack.taskData.liftingSpecification.horizontalSpeed * 1000).toInt()
    }

    override fun openCameraFinished() {
        "开启摄像头".showSnackBar()
        binding.videoView.visibility = View.VISIBLE
        binding.videoView.setVideoPath(VIDEO_URL_1)
        binding.videoView.start()
    }

    override fun closeCameraFinished() {
        "关启摄像头".showSnackBar()
        binding.videoView.visibility = View.INVISIBLE
        binding.videoView.suspend()

    }

    override fun dialogConfirmNoTask() {
        homeViewModel.isTasking.value = false
    }

    override fun stackNumberIsFinished() {
        DialogConfirmTaskFinishedFragment(this).show(parentFragmentManager)
    }

    override fun dialogConfirmTaskFinished() {
        homeViewModel.isTasking.value = false
    }
}